"use client"

import { useState } from "react"
import { Calculator, Utensils } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"

// 菜单数据
const menu = {
  meat: [
    "虾",
    "四季豆炒肉",
    "小鸡腿",
    "木耳烧排骨",
    "扣肉",
    "粉蒸肉",
    "小河鱼",
    "扇子骨",
    "蒜苔炒肉",
    "香辣凤爪",
    "红烧卢鱼",
    "小笋炒肉",
    "荷兰豆炒肉",
    "蒸蛋饺",
    "小炒肉",
  ],
  vegetables: [
    "土豆丝",
    "青菜",
    "手撕包菜",
    "娃娃菜",
    "咸鸭蛋",
    "花生米",
    "虎皮椒",
    "莴笋",
    "苦瓜",
    "皮蛋",
    "茄子",
    "红萝卜",
    "莲藕丝",
  ],
}

// 菜品的大致卡路里和营养信息（估计值）
const foodInfo = {
  虾: { calories: 120, protein: "高", fat: "低", fiber: "低", note: "富含蛋白质和矿物质" },
  四季豆炒肉: { calories: 250, protein: "中", fat: "中", fiber: "中", note: "蛋白质和膳食纤维均衡" },
  小鸡腿: { calories: 280, protein: "高", fat: "中", fiber: "低", note: "富含蛋白质" },
  木耳烧排骨: { calories: 320, protein: "高", fat: "高", fiber: "中", note: "木耳有助于降脂" },
  扣肉: { calories: 450, protein: "中", fat: "高", fiber: "低", note: "高脂肪，适量食用" },
  粉蒸肉: { calories: 380, protein: "中", fat: "高", fiber: "低", note: "高热量，减肥期间少食" },
  小河鱼: { calories: 180, protein: "高", fat: "中", fiber: "低", note: "富含优质蛋白和DHA" },
  扇子骨: { calories: 300, protein: "高", fat: "高", fiber: "低", note: "高蛋白，但脂肪含量也高" },
  蒜苔炒肉: { calories: 220, protein: "中", fat: "中", fiber: "中", note: "蒜苔含有丰富维生素" },
  香辣凤爪: { calories: 250, protein: "中", fat: "中", fiber: "低", note: "含胶原蛋白，但盐分较高" },
  红烧卢鱼: { calories: 200, protein: "高", fat: "中", fiber: "低", note: "优质蛋白来源" },
  小笋炒肉: { calories: 230, protein: "中", fat: "中", fiber: "中", note: "竹笋低热量高纤维" },
  荷兰豆炒肉: { calories: 210, protein: "中", fat: "中", fiber: "中", note: "荷兰豆富含维生素C" },
  蒸蛋饺: { calories: 180, protein: "中", fat: "低", fiber: "低", note: "低脂肪蛋白质来源" },
  小炒肉: { calories: 280, protein: "中", fat: "高", fiber: "低", note: "高脂肪，适量食用" },

  土豆丝: { calories: 120, protein: "低", fat: "低", fiber: "中", note: "富含碳水化合物和维生素C" },
  青菜: { calories: 30, protein: "低", fat: "低", fiber: "高", note: "低热量，富含维生素和矿物质" },
  手撕包菜: { calories: 45, protein: "低", fat: "低", fiber: "高", note: "低热量，高纤维" },
  娃娃菜: { calories: 35, protein: "低", fat: "低", fiber: "高", note: "低热量，富含维生素" },
  咸鸭蛋: { calories: 130, protein: "中", fat: "高", fiber: "低", note: "含钙丰富，但钠含量高" },
  花生米: { calories: 170, protein: "中", fat: "高", fiber: "中", note: "富含健康脂肪，但热量高" },
  虎皮椒: { calories: 50, protein: "低", fat: "低", fiber: "中", note: "富含维生素C" },
  莴笋: { calories: 40, protein: "低", fat: "低", fiber: "高", note: "低热量，高纤维" },
  苦瓜: { calories: 25, protein: "低", fat: "低", fiber: "中", note: "极低热量，有助于降血糖" },
  皮蛋: { calories: 120, protein: "中", fat: "中", fiber: "低", note: "含钙丰富，但钠含量高" },
  茄子: { calories: 35, protein: "低", fat: "低", fiber: "中", note: "低热量，富含膳食纤维" },
  红萝卜: { calories: 40, protein: "低", fat: "低", fiber: "高", note: "富含β-胡萝卜素和纤维" },
  莲藕丝: { calories: 80, protein: "低", fat: "低", fiber: "高", note: "富含膳食纤维和维生素C" },
}

// BMI分类
const getBMICategory = (bmi: number) => {
  if (bmi < 18.5) return { category: "体重过轻", advice: "需要适当增加营养摄入" }
  if (bmi < 24) return { category: "正常体重", advice: "保持健康饮食习惯" }
  if (bmi < 28) return { category: "超重", advice: "建议控制热量摄入，增加运动" }
  if (bmi < 30) return { category: "轻度肥胖", advice: "需要减少热量摄入，增加运动量" }
  if (bmi < 35) return { category: "中度肥胖", advice: "严格控制饮食，规律运动" }
  return { category: "重度肥胖", advice: "建议在医生指导下进行减重" }
}

// 根据BMI生成膳食建议
const generateMealPlan = (bmi: number, gender: string, mealComposition: string) => {
  // 根据BMI和性别调整每餐的卡路里目标
  let calorieTarget = 0
  let meatDishCount = 1
  let vegDishCount = 2

  // 根据用户选择设置荤素数量
  if (mealComposition === "1meat2veg") {
    meatDishCount = 1
    vegDishCount = 2
  } else if (mealComposition === "2meat1veg") {
    meatDishCount = 2
    vegDishCount = 1
  } else if (mealComposition === "2meat2veg") {
    meatDishCount = 2
    vegDishCount = 2
  }

  // 根据BMI设置卡路里目标
  if (bmi < 18.5) {
    // 体重过轻
    calorieTarget = gender === "male" ? 700 : 600
  } else if (bmi < 24) {
    // 正常体重
    calorieTarget = gender === "male" ? 650 : 550
  } else if (bmi < 28) {
    // 超重
    calorieTarget = gender === "male" ? 550 : 450
  } else {
    // 肥胖
    calorieTarget = gender === "male" ? 450 : 400
  }

  // 如果选择了两荤两素，增加卡路里目标
  if (mealComposition === "2meat2veg") {
    calorieTarget += gender === "male" ? 150 : 120
  }

  // 生成6天的午餐计划
  const mealPlan = []
  const usedMeats = new Set()
  const usedVegs = new Set()

  for (let day = 0; day < 6; day++) {
    // 选择荤菜
    const meatDishes = []
    for (let i = 0; i < meatDishCount; i++) {
      let availableMeats = menu.meat.filter((dish) => !usedMeats.has(dish))
      // 如果已经用完了所有荤菜，重置
      if (availableMeats.length === 0) {
        usedMeats.clear()
        availableMeats = menu.meat
      }

      // 根据BMI选择更健康的选项
      let selectedMeat
      if (bmi >= 24) {
        // 对于超重或肥胖的人，优先选择低热量、高蛋白的荤菜
        availableMeats.sort(
          (a, b) =>
            foodInfo[a].calories / (foodInfo[a].protein === "高" ? 2 : 1) -
            foodInfo[b].calories / (foodInfo[b].protein === "高" ? 2 : 1),
        )
        selectedMeat = availableMeats[0]
      } else {
        // 随机选择
        selectedMeat = availableMeats[Math.floor(Math.random() * availableMeats.length)]
      }

      meatDishes.push(selectedMeat)
      usedMeats.add(selectedMeat)
    }

    // 选择素菜
    const vegDishes = []
    for (let i = 0; i < vegDishCount; i++) {
      let availableVegs = menu.vegetables.filter((dish) => !usedVegs.has(dish))
      // 如果已经用完了所有素菜，重置
      if (availableVegs.length === 0) {
        usedVegs.clear()
        availableVegs = menu.vegetables
      }

      // 根据BMI选择更健康的选项
      let selectedVeg
      if (bmi >= 24) {
        // 对于超重或肥胖的人，优先选择高纤维、低热量的素菜
        availableVegs.sort(
          (a, b) =>
            foodInfo[a].calories / (foodInfo[a].fiber === "高" ? 2 : 1) -
            foodInfo[b].calories / (foodInfo[b].fiber === "高" ? 2 : 1),
        )
        selectedVeg = availableVegs[0]
      } else {
        // 随机选择
        selectedVeg = availableVegs[Math.floor(Math.random() * availableVegs.length)]
      }

      vegDishes.push(selectedVeg)
      usedVegs.add(selectedVeg)
    }

    // 计算总卡路里
    const totalCalories = [...meatDishes, ...vegDishes].reduce((sum, dish) => sum + foodInfo[dish].calories, 0)

    mealPlan.push({
      day: day + 1,
      meatDishes,
      vegDishes,
      totalCalories,
      calorieTarget,
    })
  }

  return mealPlan
}

export default function Home() {
  const [weight, setWeight] = useState("")
  const [height, setHeight] = useState("")
  const [gender, setGender] = useState("male")
  const [mealComposition, setMealComposition] = useState("1meat2veg") // 添加这一行
  const [bmi, setBMI] = useState(0)
  const [bmiCategory, setBMICategory] = useState({ category: "", advice: "" })
  const [mealPlan, setMealPlan] = useState<any[]>([])
  const [activeTab, setActiveTab] = useState("calculator")
  const [calculated, setCalculated] = useState(false)

  const calculateBMI = () => {
    if (!weight || !height) return

    const weightNum = Number.parseFloat(weight)
    const heightNum = Number.parseFloat(height) / 100 // 转换为米

    if (isNaN(weightNum) || isNaN(heightNum) || heightNum === 0) return

    const bmiValue = weightNum / (heightNum * heightNum)
    setBMI(Number.parseFloat(bmiValue.toFixed(1)))
    setBMICategory(getBMICategory(bmiValue))
    setMealPlan(generateMealPlan(bmiValue, gender, mealComposition))
    setCalculated(true)
    setActiveTab("meal-plan")
  }

  const regenerateMealPlan = () => {
    setMealPlan(generateMealPlan(bmi, gender, mealComposition))
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <h1 className="text-3xl font-bold text-center mb-8">BMI计算与健康减肥餐计划</h1>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="max-w-3xl mx-auto">
        <TabsList className="grid grid-cols-2 mb-8">
          <TabsTrigger value="calculator" className="flex items-center gap-2">
            <Calculator className="h-4 w-4" />
            <span>BMI计算器</span>
          </TabsTrigger>
          <TabsTrigger value="meal-plan" className="flex items-center gap-2" disabled={!calculated}>
            <Utensils className="h-4 w-4" />
            <span>一周午餐计划</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="calculator">
          <Card>
            <CardHeader>
              <CardTitle>BMI计算器</CardTitle>
              <CardDescription>输入您的身高、体重和性别，计算BMI指数并获取个性化的午餐计划</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-6">
                <div className="grid gap-3">
                  <Label htmlFor="weight">体重 (kg)</Label>
                  <Input
                    id="weight"
                    type="number"
                    placeholder="例如: 65"
                    value={weight}
                    onChange={(e) => setWeight(e.target.value)}
                  />
                </div>

                <div className="grid gap-3">
                  <Label htmlFor="height">身高 (cm)</Label>
                  <Input
                    id="height"
                    type="number"
                    placeholder="例如: 170"
                    value={height}
                    onChange={(e) => setHeight(e.target.value)}
                  />
                </div>

                <div className="grid gap-3">
                  <Label>性别</Label>
                  <RadioGroup value={gender} onValueChange={setGender} className="flex gap-4">
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="male" id="male" />
                      <Label htmlFor="male">男</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="female" id="female" />
                      <Label htmlFor="female">女</Label>
                    </div>
                  </RadioGroup>
                </div>

                <div className="grid gap-3">
                  <Label>午餐搭配</Label>
                  <RadioGroup value={mealComposition} onValueChange={setMealComposition} className="space-y-2">
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="1meat2veg" id="1meat2veg" />
                      <Label htmlFor="1meat2veg">一荤两素</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="2meat1veg" id="2meat1veg" />
                      <Label htmlFor="2meat1veg">两荤一素</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="2meat2veg" id="2meat2veg" />
                      <Label htmlFor="2meat2veg">两荤两素</Label>
                    </div>
                  </RadioGroup>
                </div>

                <Button onClick={calculateBMI}>计算BMI并生成餐计划</Button>

                {calculated && (
                  <div className="mt-6 p-4 border rounded-lg bg-muted/50">
                    <h3 className="text-lg font-medium mb-2">您的BMI: {bmi}</h3>
                    <p className="font-medium">分类: {bmiCategory.category}</p>
                    <p className="text-muted-foreground">{bmiCategory.advice}</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="meal-plan">
          <Card>
            <CardHeader>
              <CardTitle>一周午餐计划</CardTitle>
              <CardDescription>根据您的BMI ({bmi})，为您定制的6天健康午餐计划</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="mb-4">
                <Button onClick={regenerateMealPlan} variant="outline" className="w-full">
                  重新生成餐计划
                </Button>
              </div>

              <div className="space-y-4">
                {mealPlan.map((meal, index) => (
                  <Accordion type="single" collapsible key={index}>
                    <AccordionItem value={`day-${index}`}>
                      <AccordionTrigger className="hover:no-underline">
                        <div className="flex justify-between items-center w-full pr-4">
                          <span className="font-medium">第 {meal.day} 天午餐</span>
                          <span className="text-sm text-muted-foreground">{meal.totalCalories} 卡路里</span>
                        </div>
                      </AccordionTrigger>
                      <AccordionContent>
                        <div className="space-y-4 pt-2">
                          <div>
                            <h4 className="text-sm font-medium mb-2">荤菜</h4>
                            <div className="space-y-2">
                              {meal.meatDishes.map((dish, i) => (
                                <div key={i} className="flex justify-between items-center p-2 rounded-md bg-muted/30">
                                  <span>{dish}</span>
                                  <span className="text-sm text-muted-foreground">
                                    {foodInfo[dish].calories} 卡路里
                                  </span>
                                </div>
                              ))}
                            </div>
                          </div>

                          <div>
                            <h4 className="text-sm font-medium mb-2">素菜</h4>
                            <div className="space-y-2">
                              {meal.vegDishes.map((dish, i) => (
                                <div key={i} className="flex justify-between items-center p-2 rounded-md bg-muted/30">
                                  <span>{dish}</span>
                                  <span className="text-sm text-muted-foreground">
                                    {foodInfo[dish].calories} 卡路里
                                  </span>
                                </div>
                              ))}
                            </div>
                          </div>

                          <div className="pt-2 border-t">
                            <div className="flex justify-between items-center">
                              <span className="font-medium">总热量</span>
                              <span
                                className={`font-medium ${meal.totalCalories > meal.calorieTarget ? "text-red-500" : "text-green-500"}`}
                              >
                                {meal.totalCalories} 卡路里
                              </span>
                            </div>
                            <p className="text-sm text-muted-foreground mt-1">
                              {meal.totalCalories > meal.calorieTarget
                                ? "建议减少食用量以控制热量摄入"
                                : "热量适中，符合减肥目标"}
                            </p>
                          </div>

                          <div className="pt-2 text-sm text-muted-foreground">
                            <p>营养提示:</p>
                            <ul className="list-disc pl-5 mt-1 space-y-1">
                              {[...meal.meatDishes, ...meal.vegDishes].map((dish, i) => (
                                <li key={i}>
                                  {dish}: {foodInfo[dish].note}
                                </li>
                              ))}
                            </ul>
                          </div>
                        </div>
                      </AccordionContent>
                    </AccordionItem>
                  </Accordion>
                ))}
              </div>

              <div className="mt-6 p-4 border rounded-lg bg-muted/50">
                <h3 className="text-lg font-medium mb-2">健康饮食建议</h3>
                <ul className="space-y-2 text-sm">
                  <li>• 午餐应在11:30-13:30之间食用，避免过晚进食</li>
                  <li>• 细嚼慢咽，每口咀嚼20-30次</li>
                  <li>• 先吃蔬菜再吃肉类，有助于控制总热量摄入</li>
                  <li>• 餐后可以适当散步15-30分钟，促进消化</li>
                  <li>• 每天饮水2000ml左右，但不要在餐中大量饮水</li>
                  {bmi >= 24 && <li className="text-red-500 font-medium">• 建议控制主食摄入量，减少精制碳水化合物</li>}
                </ul>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
